package com.iot08.api.service;

import com.iot08.api.response.UserWallpaperResp;
import com.iot08.api.response.WallpaperResp;
import com.iot08.api.utils.buckettool.BaseBucketTool;
import com.iot08.api.vo.request.WallpaperQueryReqVo;
import com.iot08.common.entity.app.UserWallpaper;
import com.iot08.common.entity.app.Wallpaper;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @author cwj
 * @description
 * @date 2025/3/11 17:46
 **/
@Slf4j
@Service
public class UserWallpaperService extends BaseService<UserWallpaper> {

    @Resource
    private BaseBucketTool baseBucketTool;

    /**
     * @description 查询用户购买的壁纸信息
     * @author cwj
     * @param [openId]
     * @return java.util.List<com.iot08.common.entity.app.UserWallpaper>
     * @date @time 2025/3/11 17:52
     **/
    public List<UserWallpaper> queryUserWallpaperByOpenId(String openId) {
        Query query = new Query(Criteria.where("openid").is(openId).and("status").is(1));
        return this.find(query);
    }

    /**
     * @description
     * @author cwj
     * @param [openId]
     * @return java.util.List<com.iot08.common.entity.app.UserWallpaper>
     * @date @time 2025/3/22 9:51
     **/
    public List<UserWallpaper> queryUserWallpaperByOpenIdOrderDesc(String openId) {
        Query query = new Query(Criteria.where("openid").is(openId).and("status").is(1));
        return this.find(query.with(Sort.by(Sort.Order.desc("createTime"))));
    }
    
    /**
     * @description 查询用户购买的壁纸信息
     * @author cwj
     * @param [openId, wallpaperId]
     * @return com.iot08.common.entity.app.UserWallpaper
     * @date @time 2025/3/13 11:28
     **/
    public UserWallpaper queryUserWallpaperByOpenIdWallpaperId(String openId,String wallpaperId) {
        Query query = new Query(Criteria.where("openid").is(openId).and("wid").is(wallpaperId).and("status").is(1)).limit(1);
        return this.findOne(query);
    }

    /**
     * @description 查询用户购买的壁纸信息
     * @author cwj
     * @param [openId, wIds]
     * @return java.util.List<com.iot08.common.entity.app.UserWallpaper>
     * @date @time 2025/3/13 16:09
     **/
    public List<UserWallpaper> queryUserWallpaperByOpenIdWallpaperIds(String openId,List<String> wIds) {
        Query query = new Query(Criteria.where("openid").is(openId).and("wid").in(wIds).and("status").is(1));
        return this.find(query);
    }


    /**
     * @description 
     * @author cwj
     * @param [openId, wid]
     * @return boolean
     * @date @time 2025/3/21 10:02
     **/
    public boolean checkUserWallpaperByOpenIdWallpaperId(String openId,String wid) {
        Query query = new Query(Criteria.where("openid").is(openId).and("wid").is(wid).and("status").is(1)).limit(1);
        UserWallpaper userWallpaper = this.findOne(query);
        return !ObjectUtils.isEmpty(userWallpaper);
    }

    /**
     * @description 检查用户是否已经购买了某些壁纸，存在已经购买的返回true
     * @author cwj
     * @param [openId, wIds]
     * @return boolean
     * @date @time 2025/3/13 16:12
     **/
    public boolean checkUserWallpaperByOpenIdWallpaperIds(String openId,List<String> wIds) {
        Query query = new Query(Criteria.where("openid").is(openId).and("wid").in(wIds).and("status").is(1)).limit(1);
        UserWallpaper userWallpaper = this.findOne(query);
        return !ObjectUtils.isEmpty(userWallpaper);
    }


    /**
     * @description 保存用户购买的壁纸信息
     * @author cwj
     * @param [wallpapers, openId, orderId, status]
     * @return boolean
     * @date @time 2025/3/13 17:38
     **/
    public boolean createUserWallpaper(List<Wallpaper> wallpapers,String openId,String orderId,Integer status){
        if(!CollectionUtils.isEmpty(wallpapers)) {
            List<UserWallpaper> userWallpapers = new ArrayList<>();
            for (Wallpaper w : wallpapers) {
                UserWallpaper userWallpaper = new UserWallpaper();
                userWallpaper.setOpenid(openId);
                userWallpaper.setWid(w.getId());
                userWallpaper.setOrderid(orderId);
                userWallpaper.setStatus(status);
                userWallpaper.setCostGoldCoinNum(w.getPrice());
                userWallpaper.setCreateTime(new Date());
                userWallpaper.setUpdateTime(new Date());
                userWallpapers.add(userWallpaper);
            }
            userWallpapers = (List<UserWallpaper>) mongoTemplate.insertAll(userWallpapers);
            return !CollectionUtils.isEmpty(userWallpapers) && StringUtils.isNotEmpty(userWallpapers.get(0).getId());
        } else {
            return false;
        }
    }


    /**
     * @description
     * @author cwj
     * @param [vo]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2025/3/22 10:12
     **/
    public ResponseMap queryUserBoughtWallpaper(WallpaperQueryReqVo vo){
        if(ObjectUtils.isEmpty(vo.getPage())){
            vo.setPage(0);
        }
        if(ObjectUtils.isEmpty(vo.getNum())){
            vo.setNum(20);
        } 
        int skip = vo.getPage() * vo.getNum();
        // 1️⃣ 计算总数
        Aggregation countAggregation = Aggregation.newAggregation(
                // 筛选指定用户的 UserWallpaper 记录
                Aggregation.match(Criteria.where("openid").is(vo.getOpenid()).and("status").is(1)),

                // 关联 Wallpaper 表，转换 wid 为 ObjectId 类型
                Aggregation.project()
                        .andExpression("{$toObjectId: '$wid'}").as("widObjectId"),
                // 使用 lookup 进行关联
                Aggregation.lookup("wallpaper", "widObjectId", "_id", "wallpaperData"),
                //Aggregation.lookup("wallpaper", "wid", "_id", "wallpaperData"),

                // 展开 wallpaperData（避免空值影响）
                Aggregation.unwind("wallpaperData", true),

                // 投影出需要的字段（可以只保留 wallpaperData 的必要字段，减少计算复杂度）
                Aggregation.project("wallpaperData._id"),

                // 统计符合条件的记录数
                Aggregation.count().as("totalCount")
        );

        // 执行总数查询
        AggregationResults<Document> countResults = mongoTemplate.aggregate(countAggregation, "user_wallpaper", Document.class);
        long totalCount = 0;
        if (!countResults.getMappedResults().isEmpty()) {
            totalCount = countResults.getMappedResults().get(0).getInteger("totalCount");
        }

        Aggregation aggregation = Aggregation.newAggregation(
                // 1️⃣ 筛选指定用户的 UserWallpaper 记录
                Aggregation.match(Criteria.where("openid").is(vo.getOpenid()).and("status").is(1)),

                // 使用原生的 MongoDB 聚合操作 $toObjectId 转换 wid 字段
                Aggregation.project()
                        .andExpression("{$toObjectId: '$wid'}").as("widObjectId")
                        .and("createTime").as("userWallpaperCreateTime"),

                // 使用 lookup 进行关联
                Aggregation.lookup("wallpaper", "widObjectId", "_id", "wallpaperData"),
                // 2️⃣ 关联 Wallpaper 表
                //Aggregation.lookup("wallpaper", "wid", "_id", "wallpaperData"),

                // 3️⃣ 展开 wallpaperData（避免空值影响）
                Aggregation.unwind("wallpaperData", true),

                // 4️⃣ 投影出需要的字段
                Aggregation.project()
                        .andExpression("wallpaperData._id").as("wid")
                        .andExpression("wallpaperData.name").as("name")
                        .andExpression("wallpaperData.cid").as("cid")
                        .andExpression("wallpaperData.categoryName").as("categoryName")
                        .andExpression("wallpaperData.isFree").as("isFree")
                        .andExpression("wallpaperData.isVipFree").as("isVipFree")
                        .andExpression("wallpaperData.price").as("price")
                        .andExpression("wallpaperData.imageUrl").as("imageUrl")
                        .and("userWallpaperCreateTime").as("userWallpaperCreateTime")   // UserWallpaper 的 createTime 显示为 userWallpaperCreateTime
                        .and("wallpaperData.createTime").as("wallpaperCreateTime"),  // Wallpaper 的 createTime 显示为 wallpaperCreateTime
                // 5️⃣ 按 createTime 倒序排列
                Aggregation.sort(Sort.by(Sort.Direction.DESC, "userWallpaperCreateTime")),
                // 6️⃣ 分页处理
                Aggregation.skip(skip),
                Aggregation.limit(vo.getNum())
        );
        // 8️⃣ 执行查询
        List<UserWallpaperResp> userWallpaperList = mongoTemplate.aggregate(aggregation, "user_wallpaper", UserWallpaperResp.class).getMappedResults();
        //遍历组装壁纸url
        assembleWallpaperUrl(userWallpaperList,baseBucketTool.getDOMAIN() + BaseBucketTool.DEVICE_COMMON_PATH);
        ResponseMap res = ResponseMap.success();
        res.put("total",totalCount);
        res.put("userWallpapers",userWallpaperList);
        return res;
    }


    /**
     * @description 更新壁纸的url
     * @author cwj
     * @param [userWallpaperResps, path]
     * @return void
     * @date @time 2025/3/25 10:38
     **/
    public static void assembleWallpaperUrl(List<UserWallpaperResp> userWallpaperResps,String path) {
        if(!CollectionUtils.isEmpty(userWallpaperResps)) {
            for (UserWallpaperResp userWallpaperResp : userWallpaperResps) {
                userWallpaperResp.setImageUrl(path+userWallpaperResp.getImageUrl());
            }
        }
    }


}
